// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function () { // 通用预处理器

	},
	/**
	 * 获取列表
	 * @param {string} openid 
	 * @param {number} pageIndex 
	 * @param {number} pageSize 
	 */
	async getList(openid, pageIndex = 1, pageSize = 100) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		const res = await dbjql.collection('mysearch').where({
			onlyid: openid
		}).skip((pageIndex - 1) * pageSize).limit(pageSize).get();
		return res;
	},
	/**
	 * 获取列表
	 * @param {string} openid 
	 * @param {number} pageIndex 
	 * @param {number} pageSize 
	 */
	async getListFilterTag(openid, tags, pageIndex = 1, pageSize = 100) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		let tagsArr = [];
		if (tags.indexOf(',')) {
			tagsArr = tags.split(',');
		} else {
			tagsArr = [tags];
		}
		console.log('---- getListFilterTag ----:', tagsArr)
		const ress = {};
		for(let i=0; i<tagsArr.length; i++) {
			try{
				const res = await dbjql.collection('mysearch').where({
					onlyid: openid,
					tag: tagsArr[i]
				}).skip((pageIndex - 1) * pageSize).limit(pageSize).get();
				console.log("---- dbjql.collection('mysearch') ----:ok", res)
				if (res.errCode === 0) {
					ress[tagsArr[i]] = res.data;	
				} else {
					ress[tagsArr[i]] = null;
				}
			}catch(err){
				//TODO handle the exception
				console.log("---- dbjql.collection('mysearch') ----:fail", err)
				ress[tagsArr[i]] = null;	
			}
			
		}
		return {
			code: 200,
			data: ress
		};
	},
	
	/**
	 * 添加记录
	 * @param {Object} item
	 */
	async add(item) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		// 去重
		if (item.tag === 'trainnum') {
			const res = await dbjql.collection('mysearch').where({
				onlyid: item.onlyid,
				trainnum: item.trainnum
			}).get();
			if (res.code === 0 && res.data && res.data.length > 0) {
				const resUpdate = await dbjql.collection('mysearch').doc(res.data[0]._id).update({ date: Date.now()});
				return resUpdate;
			}
		}
		if (item.tag === 'station') {
			const res = await dbjql.collection('mysearch').where({
				onlyid: item.onlyid,
				from: item.from,
				to: item.to
			}).get();
			if (res.code === 0 && res.data && res.data.length > 0) {
				const resUpdate = await dbjql.collection('mysearch').doc(res.data[0]._id).update({ date: Date.now()});
				return resUpdate;
			}
		}
		const res = await dbjql.collection('mysearch').add({...item, date: Date.now()});
		return res;
	},
	
	/**
	 * 删除搜索记录
	 * @param {string} openid 
	 * @param {string} id 
	 */
	async delete(openid, id) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		const res = await dbjql.collection('mysearch').where({
			onlyid: openid,
			_id: id
		}).remove();
		return res;
	}
}
